package com.modai.springcloud.service;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.TimeUnit;

/**
 * @author ：modai
 * @date ：Created in 2020-12-7 18:52
 * @description：
 */
@Service
public class HystrixService {
    @Value("server.port")
    private String serverPort;

    public String responseOk(int id) {
        return ">>>>>>>>>>hello，这里是线程" + Thread.currentThread().getName() + "   id: "+id+",端口号为：" + serverPort + "目前状态OK，O(∩_∩)O";
    }

    @HystrixCommand(fallbackMethod = "responseTimeout_handler"
            , commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2")
    }
    )
    public String responseTimeout(int id) {
//        int timeout = 3;
//        try {
//            TimeUnit.SECONDS.sleep(timeout);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        int s = 10/0;
        return ">>>>>>>>>>hello，这里是线程" + Thread.currentThread().getName() + "    id: "+id+",端口号为：" + serverPort + "目前状态已经超时（s）：" +"/(ㄒoㄒ)/~~";
    }

    public String responseTimeout_handler(int id) {
        return "sorry, API调用超时或错误，查查看吧。👁👁,线程为："+Thread.currentThread().getName();
    }
    @HystrixCommand(fallbackMethod = "getNoneNegativeNumber_handler",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "10")
    })
    public String getNoneNegativeNumber(int num){
        if (num<0){
            throw new RuntimeException("数字不能小于0");
        }
        String uuid = IdUtil.simpleUUID();
        return "得到了一个非负数数"+num+"哈哈(*^_^*)"+"当前线程为"+Thread.currentThread().getName()+"; 流水号为："+uuid;
    }

    private String getNoneNegativeNumber_handler(int num){
        return "不能为负数！！！！，输入数字为："+num;
    }
}
